import os
import base64
import datetime

import requests

from functools import lru_cache
from django.http import HttpResponse
from django.conf import settings


API_KEY = base64.b64decode(
    'MTBiOTg2MDg3YzI2MzAzZjM3MGIwZDc5ODQxYWNlM2RlODg2NDZiYg==').decode()
API_URL = base64.b64decode(
    'aHR0cDovL2xpY2Vuc2UubXI0d2ViLmNvbS9hcGkvY2hlY2tfbGljZW5zZS8=').decode()


@lru_cache
def check(HOST, EV_CODE, refresh=0):
    if settings.DEBUG:
        print('checking...')
    data = {base64.b64decode(
        'bGljZW5zZV9jb2Rl').decode(): EV_CODE, 'host': HOST}
    headers = {
        'Authorization': f'Bearer {API_KEY}'
    }

    res = requests.post(API_URL, data=data, headers=headers)
    return res.json()


class LSCheckerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, req):
        HOST = f'{req.scheme}://{req.get_host()}'
        EV_CODE = os.getenv(base64.b64decode(
            'RU5WQVRPX1BVUkNIQVNFX0NPREU=').decode())

        if '/account' in req.path:
            data = {}
            try:
                data = check(
                    HOST, EV_CODE, refresh=datetime.datetime.utcnow().day)

                if data.get('status') != base64.b64decode('QUNUSVZF').decode():
                    check.cache_clear()
                    return HttpResponse("<h1>%s</h1>" % data['message'], status=401)
            except Exception as e:
                check.cache_clear()
                print('LC verification exception:', e)
                return HttpResponse("<h1>Something went wrong during the license verification, please try again/later or contact the support!</h1>", status=403)

        return self.get_response(req)
